package com.filter;

import com.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//urlPatterns:url匹配规则。可以写多个，用逗号隔开
@WebFilter(urlPatterns = {"/admin/*"})
public class Demo01Filter implements Filter {
    public Demo01Filter() {
        System.out.println("过滤器 Demo01Filter 构造函数调用");
    }

    @Override
    public void destroy() {
        System.out.println("过滤器 Demo01Filter 销毁");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("过滤器 Demo01Filter doFilter");
        //1.强转
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            System.out.println("允许通行");
            //允许进入下一个拦截器
            chain.doFilter(req, resp);
        } else {
            response.sendRedirect(request.getContextPath() + "/login.html");
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        System.out.println("过滤器 Demo01Filter 初始化");
    }

}
